package cn.myapps.demospringsecurity.utils;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSATestUtil {

    // 从后端获取公钥的接口地址
    private static final String PUBLIC_KEY_URL = "http://localhost:8080/public-key";

    // 将PEM格式公钥转换为Java PublicKey对象
    public static PublicKey getPublicKeyFromUrl() throws Exception {
        // String publicKeyPEM = fetchPublicKey(PUBLIC_KEY_URL);
        String publicKeyPEM = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0T1ZDxzbxRtOL6XhymvGphlf12gu7geAIcMeO2KTLSOuzty9c3q8PQHld76cuDFeJcgeyuMfkSKbtbo/mA7CGZc71ovpsSASxFJ+jPjKwc8T2R4pu8m4v5Z2UCe0q5XIQollWXBcqsYhWhNd0BXhZRDnM9wNb0ESBS+QmQDNISZaHaYxeafmYKT5/QUYbIUk+EZpgAUo2hHh3pbLdOkNsO5txi6bL0G200lOHK+U6cQtokWIBysw1HSK3FDGlQ4S+OEqFIzKatM8fiCOjOsbBYFZWNC+sGsmzbGRAWuFd+BA3zatqlajZHYmIkjROWTAN+c8YMcTEAVdQxWpPnCCqwIDAQAB";

        // 处理PEM格式
        String base64Key = publicKeyPEM
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", ""); // 移除所有空格换行

        byte[] decoded = Base64.getDecoder().decode(base64Key);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }

    // 拉取公钥的通用方法
    private static String fetchPublicKey(String apiUrl) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection();
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed to fetch public key: HTTP error code : " + conn.getResponseCode());
        }

        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }

    // 使用远程公钥加密数据（自动处理PEM转换）
    public static String encryptWithRemotePublicKey(String data) throws Exception {
        PublicKey publicKey = getPublicKeyFromUrl();

        // 使用PKCS1Padding填充模式（与前端JSEncrypt保持一致）
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }



    // 测试方法
    public static void main(String[] args) {
        try {
            String testData = "123456";

            // 加密测试
            String usermane = encryptWithRemotePublicKey("admin");
            String password = encryptWithRemotePublicKey("123");
            System.out.println("usermane加密结果 (Base64): " + usermane);
            System.out.println("password加密结果 (Base64): " + password);

            // 验证长度限制（2048位密钥最大加密245字节）
            // System.out.println("明文长度: " + testData.length() + " bytes");
            // System.out.println("加密后长度: " + encryptedData.length() + " bytes");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
